package day01;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

public class Demo06 {
    public static void main(String[] args) {

        /**
         * 测试 ArrayList Array HashMap 的随机读取性能:
         * - Array 数组天下第一快
         * - ArrayList 的get方法，内部就是数组下标读取，性能稍慢
         * - HashMap的get内部也是将key映射到数组下标，找到数据，比数组稍微慢一点
         */

        ArrayList<String> list = new ArrayList<>();
        String[] arr = new String[500000];
        HashMap<Integer, String> map = new HashMap<>();
        for (int i=0; i<500000;i++){
            String uuid = UUID.randomUUID().toString();
            list.add(uuid);
            arr[i] = uuid;
            map.put(i, uuid);
        }
        System.out.println("随机读取性能：");
        String s;
        long t1,t2,t3,t4,t5,t6;
        System.out.println("读取：");
        t1 = System.nanoTime();
        s = list.get(0);
        t2 = System.nanoTime();
        s = list.get(125000);
        t3 = System.nanoTime();
        s = list.get(250000);
        t4 = System.nanoTime();
        s = list.get(375000);
        t5 = System.nanoTime();
        s = list.get(499999);
        t6 = System.nanoTime();
        System.out.println("ArrayList:");
        System.out.println("0:"+(t2-t1));
        System.out.println("125000:"+(t3-t2));
        System.out.println("250000:"+(t4-t3));
        System.out.println("375000:"+(t5-t4));
        System.out.println("499999:"+(t6-t5));

        t1 = System.nanoTime();
        s = arr[0];
        t2 = System.nanoTime();
        s = arr[125000];
        t3 = System.nanoTime();
        s = arr[250000];
        t4 = System.nanoTime();
        s = arr[375000];
        t5 = System.nanoTime();
        s = arr[499999];
        t6 = System.nanoTime();
        System.out.println("Array:");
        System.out.println("0:"+(t2-t1));
        System.out.println("125000:"+(t3-t2));
        System.out.println("250000:"+(t4-t3));
        System.out.println("375000:"+(t5-t4));
        System.out.println("499999:"+(t6-t5));

        t1 = System.nanoTime();
        s = map.get(0);
        t2 = System.nanoTime();
        s = map.get(125000);
        t3 = System.nanoTime();
        s = map.get(250000);
        t4 = System.nanoTime();
        s = map.get(375000);
        t5 = System.nanoTime();
        s = map.get(499999);
        t6 = System.nanoTime();
        System.out.println("HashMap:");
        System.out.println("0:"+(t2-t1));
        System.out.println("125000:"+(t3-t2));
        System.out.println("250000:"+(t4-t3));
        System.out.println("375000:"+(t5-t4));
        System.out.println("499999:"+(t6-t5));
    }
}

